<?php
/*
 * Copyright 2007 Bjørn Tore Håvie
 * 
 * This file is part of ITSBOT.
 * 
 * ITSBOT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ITSBOT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ITSBOT.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @package ITSBOT
 * @subpackage Networking
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
/**
 * Socket
 *
 */
class Socket{
	
	private $address;
	
	private $port;
	
	private $socket;
	
	private $buffer = '';
	
	public function __construct($host, $port){
		$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
		socket_connect($this->socket, $host, $port) or die(socket_last_error($this->socket));
	}
	
	public function __destruct(){
		socket_shutdown($this->socket);
		socket_close($this->socket);
	}
	
	public function Send($data){
		return socket_write($this->socket, $data, strlen($data));
	}
	
	public function Read($len = 1024){
		$this->buffer .= socket_read($this->socket, $len, PHP_BINARY_READ);
		if(!empty($this->buffer) && ($pos = strpos($this->buffer, "\r\n")) !== false){
			$tmp = substr($this->buffer, 0, $pos);
			$this->buffer = substr($this->buffer, $pos + 2);
			return $tmp;
		}
		return false;
	}
	
	public function SetBlocking($b){
		if($b)
			return socket_set_block($this->socket);
		else
			return socket_set_nonblock($this->socket);
	}

}
?>